<template>
  <div class="dict-type-manage">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
      <el-form-item label="字典名称" prop="dictName">
        <el-input
          v-model="queryParams.dictName"
          placeholder="请输入字典名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input
          v-model="queryParams.dictType"
          placeholder="请输入字典类型"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="字典状态" clearable style="width: 200px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" v-permission="'admin:user/dict_type:add'" plain icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="danger" v-permission="'admin:user/dict_type:del'" plain icon="Delete" :disabled="multiple" @click="handleAllDelete">
        删除
      </el-button>
      <!-- <el-button type="warning" plain icon="Download">导出</el-button> -->
      <el-button type="info" plain icon="Refresh" @click="refreshCache">刷新缓存</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="dictTypeList"
      @selection-change="handleSelectionChange"
      class="data-table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编号" align="center" prop="dict_id" width="100" />
      <el-table-column label="字典名称" align="center" prop="dict_name" :show-overflow-tooltip="true" />
      <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
            <span style="cursor: pointer;color: #409eff;" @click="route_link(scope.row)">{{ scope.row.dict_type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status == '0' ? 'success' : 'danger'">
            {{ scope.row.status == '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ (scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit"  v-permission="'admin:user/dict_type:edit'" @click="handleUpdate(scope.row)" />
          </el-tooltip>
          <el-tooltip content="删除" placement="top" >
            <el-button link type="danger" icon="Delete" v-permission="'admin:user/dict_type:del'" @click="handleDelete(scope.row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加或修改对话框 -->
    <DictModal
      v-model:visible="dialog.visible"
      :type="dialog.type"
      :form-data="dialog.formData"
      @success="handleModalSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { DictType, DictQueryParams, DictTypeForm } from '@/types/dict'
import { dictTypeApi } from '@/api/dict'
import DictModal from './DictModal.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const dictTypeList = ref<DictType[]>([])
const total = ref(0)
const multiple = ref(true)
const ids = ref<number[]>([])

// 查询参数
const queryParams = reactive<DictQueryParams>({
  pageNum: 1,
  pageSize: 10,
  dictName: '',
  dictType: '',
  status: ''
})

// 对话框状态
const dialog = reactive({
  visible: false,
  type: 'add' as 'add' | 'edit',
  formData: {} as DictTypeForm
})

const queryFormRef = ref()

// 方法
const getList = async () => {
  loading.value = true
  try {
    const { data } = await dictTypeApi.getList(queryParams)
    dictTypeList.value = data.rows||[]
    total.value = data.total||0
  } catch (error) {
    console.error('获取字典类型列表失败:', error)
  } finally {
    loading.value = false
  }
}

const route_link = (row: any) => {
  //使用路由跳转
  router.push({
    path: '/user/dict_type',
    query: {
      dictType: row.dict_type,
      rand: Math.floor(Math.random() * 100)
    }
  })
}


const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleAdd = () => {
  dialog.visible = true
  dialog.type = 'add'
  dialog.formData = {
    dictName: '',
    dictType: '',
    status: '0',
    remark: ''
  }
}

const handleUpdate = (row: any) => {
  dialog.visible = true
  dialog.type = 'edit'
  
  row.dictName = row.dict_name
  row.dictType = row.dict_type
  row.status = row.status.toString()

  dialog.formData = { ...row }
}

const handleDelete = async (row?: any) => {
  const dictIds = row.dict_id
  if (dictIds.length === 0) {
    ElMessage.warning('请选择要删除的字典类型')
    return
  }

  console.log(dictIds)

  try {
    await ElMessageBox.confirm('是否确认删除字典编号为"' + dictIds + '"的数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await dictTypeApi.delete(dictIds)
    ElMessage.success('删除成功')
    getList()
  } catch (error:any) {
    console.error('删除失败:', error)
    if(error.code == 500||error.code == 400){
      ElMessage.error(error.message)
    }
  }
}

const handleAllDelete = async () => {
  const dictIds = ids.value
  if (dictIds.length === 0) {
    ElMessage.warning('请选择要删除的字典类型')
    return
  }

  try {
    await ElMessageBox.confirm('是否确认删除选中的数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await dictTypeApi.delete(dictIds)
    ElMessage.success('删除成功')
    getList()
  } catch (error:any) {
    console.error('删除失败:', error)
    if(error.code == 500||error.code == 400){
      ElMessage.error(error.message)
    }
  }
}

const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.dict_id)
  multiple.value = !selection.length
}

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

const handleModalSuccess = () => {
  dialog.visible = false
  getList()
}

const refreshCache = async () => {
  try {
    await dictTypeApi.refreshCache()
    ElMessage.success('刷新缓存成功')
  } catch (error) {
    console.error('刷新缓存失败:', error)
  }
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.dict-type-manage {
  padding: 20px;

  .search-form {
    margin-bottom: 20px;
  }

  .operation-buttons {
    margin-bottom: 20px;

    .el-button {
      margin-right: 10px;
    }
  }

  .data-table {
    margin-bottom: 20px;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }

  .link-type {
    color: var(--el-color-primary);
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style>